package cn.bxshey.resourceSharing.service.impl;

import cn.bxshey.resourceSharing.entity.User;
import cn.bxshey.resourceSharing.mapper.UserMapper;
import cn.bxshey.resourceSharing.service.LoginService;
import cn.bxshey.resourceSharing.utils.JwtUtils;
import cn.bxshey.resourceSharing.utils.MyMail;
import cn.bxshey.resourceSharing.utils.RedisUtils;
import cn.bxshey.resourceSharing.vo.user.LoginVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.util.*;

/**
 * @作者：不想说话而已
 * @Date：2023/12/18 10:55
 */
@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {

    @Resource
    UserMapper userMapper;

    @Resource
    RedisUtils redisUtils;

    @Resource
    MyMail mail;

    //登录
    @Override
    public Map<String, Object> login(Map<String, String> info) {

        User user = userMapper.getUserByName(info.get("auto"));
        if(Objects.isNull(user) || !BCrypt.checkpw(info.get("password"), user.getPassword())){
            return null;
        }

        if(!redisUtils.checkValue(RedisUtils.LOGIN_CAPTCHA,info.get("captchaId"),info.get("captcha"))){
            return null;
        }

        Map<String,String> tokenInfo = new HashMap<>();
        tokenInfo.put("id", String.valueOf(user.getId()));
        tokenInfo.put("username", String.valueOf(user.getUsername()));

        Map<String,Object> userInfo = new HashMap<>();
        LoginVO userVO = new LoginVO();
        BeanUtils.copyProperties(user,userVO);
        userInfo.put("token",JwtUtils.createToken(tokenInfo));
        userInfo.put("info",userVO);
        return userInfo;
    }

    //退出登录
    @Override
    public Map<String, Object> logout() {
        Map<String,Object> userInfo = new HashMap<>();
        userInfo.put("info","退出成功");
        return userInfo;
    }

    //登录验证码
    @Override
    public Map<String,String> captcha() {
        String captcha = mail.myMailCaptcha();
        String id = String.valueOf(UUID.randomUUID());
        redisUtils.addValue(RedisUtils.LOGIN_CAPTCHA,id,captcha,60L);
        Map<String,String> info = new HashMap<>();
        info.put("captcha",captcha);
        info.put("captchaId",id);
        return info;
    }


    //随机注册验证码
    @Override
    public void captchaEnroll(String email) throws MessagingException {
        String captcha = mail.myMailCaptcha();
        redisUtils.addValue(RedisUtils.LOGIN_ENROLL,email, captcha,300L);
        System.out.println("登录验证码："+captcha);
        mail.sendSimpleMail("注册验证码",email,captcha,false);
    }
}
